<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | TableBackuper.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-10-13
// +-------------------------------------------------------------------------------


namespace app\extend\db;

use think\Config;
use think\Db;
use think\Exception;

/**
 * 数据表备份类
 *
 * @package app\extend\db
 */
class TableBackupHelper {

    /**
     * 备份数据表
     *
     * @param string $name 不带前缀的表名
     * @param string $saveDirPath
     * @throws Exception
     */
    public static function backup($name, $saveDirPath) {
        $prefix = Config::get("database.prefix");
        $tableName = $prefix . $name;

        self::backupWithTableName($tableName, $saveDirPath);
    }

    /**
     * 备份数据表
     *
     * @param string $tableName 带前缀的表名
     * @param string $saveDirPath
     * @throws Exception
     */
    public static function backupWithTableName($tableName, $saveDirPath) {
        $filePath = $saveDirPath . DS . $tableName . "_" . date('YmdHis') . ".sql";
        $fileWriter = fopen($filePath, "w");
        if (!$fileWriter) {
            throw new Exception("file " . $filePath . " can not be write.");
        }

        //写入Drop Table语句
        fwrite($fileWriter, "DROP TABLE IF EXISTS `" . $tableName . "`;\r\n");
        //写入Create Table语句
        $tableSqlInfo = Db::query("show create table `" . $tableName . "`;");
        if (empty($tableSqlInfo)) {
            throw new Exception("table " . $tableName . " not found.");
        }
        $tableSql = $tableSqlInfo[0]["Create Table"];
        fwrite($fileWriter, $tableSql . ";\r\n");
        //写入insert语句
        $pdo = Db::getPdo();
        $resultSet = $pdo->query("select * from `" . $tableName . "`");
        while ($row = $resultSet->fetch(\PDO::FETCH_ASSOC)) {
            $fieldNames = array_keys($row);
            $fieldValues = array_values($row);

            $fieldNamesStr = '';
            foreach ($fieldNames as $key => $value) {
                $fieldNamesStr .= "`" . $value . "`,";
            }
            $fieldNamesStr = substr($fieldNamesStr, 0, strlen($fieldNamesStr) - 1);


            $fieldValuesStr = '';
            foreach ($fieldValues as $key => $value) {
                $fieldValuesStr .= "'" . $value . "',";
            }
            $fieldValuesStr = substr($fieldValuesStr, 0, strlen($fieldValuesStr) - 1);
            $sql = "insert into `{$tableName}`({$fieldNamesStr}) values({$fieldValuesStr})";
            fwrite($fileWriter, $sql . ";\r\n");
        }
        fclose($fileWriter);
    }
}